#include "Configmanager.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

ConfigManager& ConfigManager::instance()
{
    static ConfigManager instance;
    return instance;
}

bool ConfigManager::loadConfig(const QString& path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开配置文件:" << path;
        return false;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    QString jsonStr = in.readAll();
    file.close();

    try {
        m_config = json::parse(jsonStr.toStdString());
        return true;
    } catch (json::exception& e) {
        qWarning() << "JSON 解析失败:" << e.what();
        return false;
    }
}

json* ConfigManager::findJsonByPath(const QString& keyPath)
{
    QStringList keys = keyPath.split(".");
    json* current = &m_config;

    for (const QString& key : keys) {
        if (!current->contains(key.toStdString()))
            return nullptr;
        current = &(*current)[key.toStdString()];
    }

    return current;
}

QString ConfigManager::getString(const QString& keyPath, const QString& defaultValue)
{
    json* node = findJsonByPath(keyPath);
    return (node && node->is_string()) ? QString::fromStdString(node->get<std::string>()) : defaultValue;
}

int ConfigManager::getInt(const QString& keyPath, int defaultValue)
{
    json* node = findJsonByPath(keyPath);
    return (node && node->is_number_integer()) ? node->get<int>() : defaultValue;
}

bool ConfigManager::getBool(const QString& keyPath, bool defaultValue)
{
    json* node = findJsonByPath(keyPath);
    return (node && node->is_boolean()) ? node->get<bool>() : defaultValue;
}
